package com.yt.db.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * Zookeeper配置类
 */
@Slf4j
@Configuration
public class ZookeeperConfig {

    private static final String ZK_ADDRESS = "127.0.0.1:2181";
    private static final int SESSION_TIMEOUT = 5000;

    @Bean
    public ZooKeeper zooKeeper() {
        CountDownLatch latch = new CountDownLatch(1);
        ZooKeeper zk = null;
        try {
            zk = new ZooKeeper(ZK_ADDRESS, SESSION_TIMEOUT, new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    if (event.getState() == Event.KeeperState.SyncConnected) {
                        log.info("Connected to Zookeeper at {}", ZK_ADDRESS);
                        latch.countDown();
                    } else if (event.getState() == Event.KeeperState.Disconnected) {
                        log.warn("Disconnected from Zookeeper at {}", ZK_ADDRESS);
                    } else if (event.getState() == Event.KeeperState.Expired) {
                        log.error("Session expired with Zookeeper at {}", ZK_ADDRESS);
                    }
                }
            });
            latch.await();
        } catch (IOException | InterruptedException e) {
            log.error("Failed to connect to Zookeeper at {}", ZK_ADDRESS, e);
        }
        return zk;
    }
}